/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.purpose.service.impl;

import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.purpose.domain.ContractTemplate;
import com.koron.purpose.mapper.ContractTemplateMapper;
import com.koron.purpose.service.api.ContractTemplateService;
import com.koron.purpose.utils.BusinessCode;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ContractTemplateServiceImpl implements ContractTemplateService {

    private final static  Logger logger = LoggerFactory.getLogger(ContractTemplateServiceImpl.class);

    @Override
    public DataBean<ContractTemplate> fetchContractTemplates(String year, String name, Integer start, Integer rows) {
        if (logger.isDebugEnabled()) {
            logger.debug("year = {}, name = {}", year, name);
        }
        try (SessionFactory factory = new SessionFactory()) {
            ContractTemplateMapper mapper = factory.getMapper(ContractTemplateMapper.class);
            List<ContractTemplate> templates = mapper.queryByCondition(year, name, start, rows);
            Integer total = mapper.countByCondition(year, name);
            DataBean<ContractTemplate> dataBean = new DataBean<>();
            dataBean.setList(templates);
            dataBean.setPageSize(rows);
            dataBean.setTotalNumber(total);
            dataBean.setTotalPage(total > rows ? (total % rows == 0? total/rows : total/rows + 1) : 1);
            dataBean.setPageNo(start / rows + 1);
            return dataBean;
        }
    }

    @Override
    public ContractTemplate fetchOne(String id) {
        if (logger.isDebugEnabled()) {
            logger.debug("id = {}", id);
        }
        try (SessionFactory factory = new SessionFactory()) {
            return factory.getMapper(ContractTemplateMapper.class).queryOne(id);
        }
    }

    @Override
    public Boolean batchDetele(List<String> idList) {
        try (SessionFactory factory = new SessionFactory()) {
            return factory.getMapper(ContractTemplateMapper.class).batchDetele(idList) >= 0;
        }
    }

    @Override
    public Integer persist(ContractTemplate template) {
        try (SessionFactory factory = new SessionFactory()) {
            Integer start = null, rows = null;
            ContractTemplate dest = null;
            ContractTemplateMapper mapper = factory.getMapper(ContractTemplateMapper.class);
            List<ContractTemplate> templates = mapper.queryByCondition(template.getYear(), template.getName(), start, rows);
            if (templates != null && !templates.isEmpty()) {
                templates = templates.stream().filter(t -> t.getName().equals(template.getName())).collect(Collectors.toList());
                dest = !templates.isEmpty()? templates.get(0) : null;
            }
            if (StringUtils.isBlank(template.getId())) {
                if (dest != null) {
                    return BusinessCode.CONTRACT_NAME_DUP.getCode();
                }
                template.setId(DefaultIdGenerator.getInstance().generateLongId());
                if (mapper.insert(template) > 0) {
                    return BusinessCode.SUCCESS.getCode();
                }
            } else {
                if (dest != null && !dest.getId().equals(template.getId())) {
                    return BusinessCode.CONTRACT_NAME_DUP.getCode();
                }
                if(mapper.update(template) > 0) {
                    return BusinessCode.SUCCESS.getCode();
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return BusinessCode.EXCEPTION.getCode();
    }



}
